package com.shujia.core

import java.util.Properties

import org.apache.flink.api.common.serialization.SimpleStringSchema
import org.apache.flink.contrib.streaming.state.RocksDBStateBackend
import org.apache.flink.runtime.state.StateBackend
import org.apache.flink.streaming.api.CheckpointingMode
import org.apache.flink.streaming.api.environment.CheckpointConfig
import org.apache.flink.streaming.api.environment.CheckpointConfig.ExternalizedCheckpointCleanup
import org.apache.flink.streaming.api.scala._
import org.apache.flink.streaming.connectors.kafka.FlinkKafkaProducer.Semantic
import org.apache.flink.streaming.connectors.kafka.{FlinkKafkaConsumer, FlinkKafkaProducer}

object Demo6SInkKafka {
  def main(args: Array[String]): Unit = {
    val env: StreamExecutionEnvironment = StreamExecutionEnvironment.getExecutionEnvironment



    // 每 1000ms 开始一次 checkpoint
    env.enableCheckpointing(20000)

    // 高级选项：

    // 设置模式为精确一次 (这是默认值)
    env.getCheckpointConfig.setCheckpointingMode(CheckpointingMode.EXACTLY_ONCE)

    // 确认 checkpoints 之间的时间会进行 500 ms
    env.getCheckpointConfig.setMinPauseBetweenCheckpoints(500)

    // Checkpoint 必须在一分钟内完成，否则就会被抛弃
    env.getCheckpointConfig.setCheckpointTimeout(60000)

    // 同一时间只允许一个 checkpoint 进行
    env.getCheckpointConfig.setMaxConcurrentCheckpoints(1)


    val config: CheckpointConfig = env.getCheckpointConfig
    //任务失败后自动保留最新的checkpoint文件
    config.enableExternalizedCheckpoints(ExternalizedCheckpointCleanup.RETAIN_ON_CANCELLATION)

    //设置状态后端，保存状态的位置
    val stateBackend: StateBackend = new RocksDBStateBackend("hdfs://master:9000/flink/checkpoint", true)
    env.setStateBackend(stateBackend)


    val properties = new Properties()
    properties.setProperty("bootstrap.servers", "master:9092")
    properties.setProperty("group.id", "asdasdas")

    //创建flink kafka 消费者
    val flinkKafkaConsumer = new FlinkKafkaConsumer[String]("exactly_once", new SimpleStringSchema(), properties)


    //如果有checkpoint，不是读取最新的数据，而是从checkpoint的位置读取数据
    flinkKafkaConsumer.setStartFromLatest()


    val kafkaDS: DataStream[String] = env.addSource(flinkKafkaConsumer)


    val wordsDS: DataStream[String] = kafkaDS.flatMap(_.split(","))


    //将数据写回到kafka中

    //会导致数据重复
    /* val myProducer = new FlinkKafkaProducer[String](
       "master:9092", // broker 列表
       "sink_kafka", // 目标 topic
       new SimpleStringSchema) // 序列化 schema
      */


    val properties1 = new Properties
    properties1.setProperty("bootstrap.servers", "master:9092")

    //事务的超时时间
    properties1.setProperty("transaction.timeout.ms", 5 * 60 * 1000 + "")

    //创建生产者
    val myProducer = new FlinkKafkaProducer[String](
      "sink_kafka", // 目标 topic
      new SimpleStringSchema,
      properties1,
      null, //分区方法
      Semantic.EXACTLY_ONCE, // 唯一一次
      5
    ) // 序列化 schema


    wordsDS.addSink(myProducer)


    env.execute()


  }
}
